using System.Linq;
using mock_ehr_lib.Model;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using cli_lib;
using System.Xml;
using mock_ehr_lib.Model.Summary;

namespace mock_ehr_lib.Data
{
    public class JsonPatientRepository : IPatientRepository
    {
        private IEnumerable<Patient> _patients;

        public JsonPatientRepository(string filename)
        {
            initialize(filename);
        }

        /// <summary>
        /// Parse a json file with patients
        /// </summary>
        /// <param name="filename">Absolute or relative path to json file</param>
        void initialize(string filename)
        {
            if(!File.Exists(filename)) throw new FileNotFoundException("Patient JSON repository file not found.");
            var jsonFile = File.ReadAllText(filename);
            var patientsJobject = JObject.Parse(jsonFile);
            var patientTokens = patientsJobject["Patients"].Children().ToList();
            var patientsList = new List<Patient>();
            int currentPatientID = 0;
            foreach(var patientToken in patientTokens)
            {
                // Custom deserialization
                var patient = new Patient
                                  {
                                      ID = ++currentPatientID,
                                      FirstName = patientToken["FirstName"].ToString(),
                                      LastName = patientToken["LastName"].ToString(),
                                      DOB = DateTime.Parse(patientToken["DOB"].ToString())
                                  };
                // CCR and CCD paths will be relative to file location
                var rootPath = Path.GetDirectoryName(Path.GetFullPath(filename)) + "\\";
                var ccrFilename = patientToken["CCR"] == null ? null : (rootPath + patientToken["CCR"]);
                if(!string.IsNullOrWhiteSpace(ccrFilename))
                {
                    var ccrSerializer = new ContinuityOfCareRecordSerializer();
                    patient.CCR = ccrSerializer.Deserialize(ccrFilename);
                    patient.Summary = PatientSummary.FromCCR(patient.CCR);
                }
                var ccdFilename = patientToken["CCD"] == null ? null : (rootPath + patientToken["CCD"]);
                if (!string.IsNullOrWhiteSpace(ccdFilename))
                {
                    // parse ccd
                    patient.CCD = File.ReadAllText(ccdFilename);
                    var doc = new XmlDocument();
                    doc.Load(ccdFilename);
                    patient.Summary = PatientSummary.FromCCDXml(doc);
                    
                }
                patient.Summary.ID = currentPatientID;
                patientsList.Add(patient);
            }
            _patients = patientsList;
        }

        public IEnumerable<Patient> GetAllPatients()
        {
            return _patients;
        }
    }
}
